﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OpenQuarters.EntityBase;
using OpenQuarters.WebQuarters.Utils;

namespace OpenQuarters.WebQuarters.Core
{
    public partial class EventLog : CMSEntity<EventLog, long>
    {
        public static EventLog Add(string Message)
        {
            return Add(EventLogPriority.M, Message);
        }

        public static EventLog Add(EventLogPriority Priority, string Message)
        {
            return Add(Priority, "", "", Message);
        }

        public static EventLog Add(EventLogPriority Priority, string Category, string Target, string Message)
        {
            EventLog log = new EventLog()
            {
                Priority = Priority.ToString()[0],
                Category = Category,
                Target = Target,
                Message = Message,
                DateCreated = DateTime.UtcNow,
                UserId = Core.User.Current.UserId,
                Url = HttpContext.Current.Request.RawUrl,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                SessionId = HttpContext.Current.Session.SessionID
            };
            log.Save();
            return log;
        }

        public override void OnDeleted()
        {
            return;
        }

        public override void OnDeleting()
        {
            return;
        }

        public override void OnLoading()
        {
            return;
        }

        public override void OnSaved()
        {
            return;
        }

        public override void OnSaving()
        {
            return;
        }

        public static EventLog Add(EventLogPriority Priority, string Category, string Target, Exception ex)
        {
            return Add(Priority, Category, Target, GeneralUtils.DescribeException(ex));
        }

        public static EventLog Add(EventLogPriority Priority, string Category, string Target, string Message, Exception ex)
        {
            return Add(Priority, Category, Target, Message + "\n" + GeneralUtils.DescribeException(ex));
        }

        public override long GetKey(EventLog Entity)
        {
            return Entity.EventId;
        }

        public override System.Linq.Expressions.Expression<Func<EventLog, bool>> GetIDSelector(long ID)
        {
            return e => e.EventId == ID;
        }
    }

    public enum EventLogPriority
    {
        L,
        M,
        H
    }
}
